package com.scorpio.sdk.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.scorpio.common.exception.CustomException;
import com.scorpio.common.utils.DateUtils;
import com.scorpio.common.utils.ServletUtils;
import com.scorpio.common.utils.StringUtils;
import com.scorpio.common.utils.ip.IpUtils;
import com.scorpio.redis.RedisCache;
import com.scorpio.redis.cachelock.RedisLock;
import com.scorpio.redis.constant.AppCacheConstant;
import com.scorpio.redis.constant.AppConfigConstant;
import com.scorpio.sdk.constant.AliYunConstant;
import com.scorpio.sdk.service.AliYunService;
import com.scorpio.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class AliYunServiceImpl implements AliYunService {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RedisLock redisLock;

    @Autowired
    private ISysConfigService sysConfigService;

    @Override
    public void sendCodeSms(String mobile, String code) {
        String openSmsSend = sysConfigService.selectConfigByKey(AppConfigConstant.CONFIG_OPEN_SMS_SEND);
        if (!"0".equals(openSmsSend)) {
            return;
        }
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        String key = "sendCodeSms:" + mobile;
        String cache = AppCacheConstant.SMS_TODAY_TOTAL + DateUtils.getDate() + ":" + mobile;
        String cacheip = AppCacheConstant.SMS_TODAY_TOTAL + DateUtils.getDate() + ":" + ip;
        if (redisLock.lock(key, 5)) {
            try {
                Integer smsTotal = sysConfigService.selectConfigIntByKey(AppConfigConstant.CONFIG_TODAY_SEND_SMS_TOTAL);
                Integer total = redisCache.getCacheObject(cache);
                Integer totalip = redisCache.getCacheObject(cacheip);
                if (total != null && total > (smsTotal <= 0 ? 0 : smsTotal)) {
                    throw new CustomException("今日短信验证码发送超出上线");
                }
                if (totalip != null && totalip > 20) {
                    throw new CustomException("您今日已被禁止发短信");
                }
                String templateCode = sysConfigService.selectConfigByKey(AliYunConstant.ALIYUN_SMS_TEMPLATECODE);
                JSONObject json = new JSONObject();
                json.put("code", code);
                sendSms(mobile, templateCode, json.toJSONString());
                redisCache.increment(cache, 1);
                redisCache.increment(cacheip, 1);
                redisCache.expire(cache, 1, TimeUnit.DAYS);
                redisCache.expire(cacheip, 1, TimeUnit.DAYS);
            } finally {
                redisLock.unlock(key);
            }
        } else {
            new CustomException("请稍后再试");
        }
    }

    @Override
    public void sendSms(String mobile, String templateCode, String templateParam) {
        String accessKeyId = sysConfigService.selectConfigByKey(AliYunConstant.ALIYUN_OSS_ACCESSKEYID);
        String accessSecret = sysConfigService.selectConfigByKey(AliYunConstant.ALIYUN_OSS_ACCESSKEYSECRET);
        String signName = sysConfigService.selectConfigByKey(AliYunConstant.ALIYUN_SMS_SIGNNAME);
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        if (!StringUtils.isEmpty(templateParam)) {
            request.putQueryParameter("TemplateParam", templateParam);
        }
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            JSONObject body = JSONObject.parseObject(data);
            if (!"OK".equals(body.getString("Code"))) {
                throw new CustomException("短信发送失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("短信发送失败", e);
        }
    }

}
